package com.towker.web;

import javax.servlet.http.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 扩展request的功能
 * @author skey
 * @version 2
 */
public class MyRequest
{
	private HttpServletRequest request;

	public MyRequest(HttpServletRequest request)
	{
		this.request = request;
	}

	/**
	 * 过滤script|iframe|\\||;|exec|insert|select|delete|update|count|chr|mid|truncate|char字符串 防止注入
	 * @param str
	 * @return
	 */
	private String filterInject(String str)
	{
		String injectstr = "script|iframe|\\||exec|insert|select|delete|update|count|chr|mid|truncate|char";
		Pattern regex = Pattern.compile(injectstr, Pattern.CANON_EQ | Pattern.DOTALL | Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
		Matcher matcher = regex.matcher(str);
		str = matcher.replaceAll("");
		str = str.replace("'", "’");
		str = str.replace(";", "；");
		str = str.replace("\"", "“");
		str = str.replace("<", "＜");
		str = str.replace(">", "＞");
		str = str.replace("+", "＋");
		str = str.replace("-", "—");
		str = str.replace("(", "（");
		str = str.replace(")", "）");
		str = str.replace("%", "％");
		str = str.replace("*", "＊");
		return str;
	}

	/**
	 * 以分隔符取得多个同名参数值
	 * @param key 参数名
	 * @param separator 分隔符
	 * @param isSecure 是否过滤安全字符
	 * @return String
	 */
	public String getStringValues(String key, String separator, boolean isSecure)
	{
		StringBuffer value = new StringBuffer();
		String _v[] = request.getParameterValues(key);
		if (_v != null && _v.length > 0)
		{
			if (isSecure)
			{
				value.append(filterInject(String.valueOf(_v[0]).replaceAll(separator, "")));
				for (int i = 1; i < _v.length; i++)
				{
					value.append(separator);
					value.append(filterInject(String.valueOf(_v[i]).replaceAll(separator, "")));
				}
			}
			else
			{
				value.append(String.valueOf(_v[0]).replaceAll(separator, ""));
				for (int i = 1; i < _v.length; i++)
				{
					value.append(separator);
					value.append(String.valueOf(_v[i]).replaceAll(separator, ""));
				}
			}
		}
		return value.toString();
	}

	/**
	 * 以分隔符取得多个同名参数值
	 * @param key 参数名
	 * @param separator 分隔符
	 * @return String
	 */
	public String getStringValues(String key, String separator)
	{
		return getStringValues(key, separator, false);
	}

	/**
	 * 以","分隔符取得多个同名参数值
	 * @param key
	 * @return String
	 */
	public String getStringValues(String key)
	{
		return getStringValues(key, ",", false);
	}

	/**
	 * 返回数组取得多个同名参数值
	 * @param key
	 * @return String[]
	 */
	public String[] getStringArray(String key)
	{
		try
		{
			String _v[] = request.getParameterValues(key);
			if (_v != null && _v.length > 0)
			{
				for (int i = 0; i < _v.length; i++)
				{
					if (_v[i] == null)
						_v[i] = "";
				}
				return _v;
			}
		}
		catch (Exception e)
		{
		}
		return new String[0];
	}

	/**
	 * 返回数组取得多个同名参数值
	 * @param key
	 * @param trimEmpty 是否去掉空值
	 * @param isSecure 是否过滤安全字符
	 * @return String[]
	 */
	public String[] getStringArray(String key, boolean trimEmpty, boolean isSecure)
	{
		if (!trimEmpty)
			return getStringArray(key);
		try
		{
			String _v[] = request.getParameterValues(key);
			if (_v != null && _v.length > 0)
			{
				List<String> list = new ArrayList<String>();
				for (int i = 0; i < _v.length; i++)
				{
					if (_v[i] == null || _v[i].trim().length() == 0)
						continue;
					if (isSecure)
						list.add(filterInject(_v[i].trim()));
					else
						list.add(_v[i].trim());
				}
				_v = new String[list.size()];
				for (int i = 0; i < list.size(); i++)
				{
					_v[i] = list.get(i);
				}
				return _v;
			}
		}
		catch (Exception e)
		{
		}
		return new String[0];
	}

	/**
	 * 返回数组取得多个同名参数值
	 * @param key
	 * @param hasEmpty 是否去掉空值
	 * @return String[]
	 */
	public String[] getStringArray(String key, boolean hasEmpty)
	{
		return getStringArray(key, hasEmpty, false);
	}

	/**
	 * 取字符串类型的参数。 如果取得的值为null，则返回默认字符串。
	 * @param key 字段名成
	 * @param defaultValue
	 * @return String
	 */
	public String getString(String key, String defaultValue)
	{
		String value = "";
		value = request.getParameter(key);
		if (value == null || value == "")
			return defaultValue;
		else
			return value;
	}

	/**
	 * 取字符串类型的参数。 如果取得的值为null，则返回空字符串。
	 * @param key
	 * @return String
	 */
	public String getString(String key)
	{
		return getString(key, "");
	}

	/**
	 * 取得安全字符串。
	 * @param request
	 * @param key
	 * @param defaultValue
	 * @return String
	 */
	public String getSecureString(String key, String defaultValue)
	{
		String value = request.getParameter(key);
		if (value == null)
		{
			return defaultValue;
		}
		else
		{
			return filterInject(value);
		}
	}

	/**
	 * 取得安全字符串，防止程序sql注入，脚本攻击。
	 * @param key
	 * @return String
	 */
	public String getSecureString(String key)
	{
		return getSecureString(key, "");
	}

	/**
	 * 返回数组取得多个同名参数值
	 * @param key
	 * @param defaultValue 用于转换失败时作为默认值
	 * @return int[]
	 */
	public int[] getIntArray(String key, int defaultValue)
	{
		try
		{
			String _v[] = request.getParameterValues(key);
			if (_v != null && _v.length > 0)
			{
				int[] _numArr = new int[_v.length];
				for (int i = 0; i < _v.length; i++)
				{
					try
					{
						_numArr[i] = Integer.parseInt(_v[i]);
					}
					catch (NumberFormatException e)
					{
						_numArr[i] = defaultValue;
					}
				}
				return _numArr;
			}
		}
		catch (Exception e)
		{
		}
		return new int[0];
	}

	/**
	 * 从request中取得int值,如果无值则返回缺省值
	 * @param key
	 * @param defaultValue
	 * @return
	 */
	public int getInt(String key, int defaultValue)
	{
		try
		{
			if (request.getParameter(key) == null)
			{
				return defaultValue;
			}
			else
			{
				String str = request.getParameter(key);
				if (str.trim().equals(""))
					return defaultValue;
				return Integer.parseInt(request.getParameter(key));
			}
		}
		catch (Exception ex)
		{
			return 0;
		}
	}

	/**
	 * 从request中取得int值
	 * @param key
	 * @return
	 */
	public int getInt(String key)
	{
		return getInt(key, 0);
	}

	/**
	 * 返回数组取得多个同名参数值
	 * @param key
	 * @param defaultValue 用于转换失败时作为默认值
	 * @return long[]
	 */
	public long[] getLongArray(String key, long defaultValue)
	{
		String _v[] = request.getParameterValues(key);
		
		if (_v != null && _v.length > 0)
		{
			long[] _numArr = new long[_v.length];
			for (int i = 0; i < _v.length; i++)
			{
				try
				{
					_numArr[i] = Long.parseLong(_v[i]);
				}
				catch (NumberFormatException e)
				{
					_numArr[i] = defaultValue;
				}
			}
			return _numArr;
		}
		
		return new long[0];
	}

	/**
	 * 从Request中取得long值,如果无值则返回缺省值
	 * @param key
	 * @return long
	 */
	public long getLong(String key, long defaultValue)
	{
		try
		{
			if (request.getParameter(key) == null)
			{
				return defaultValue;
			}
			else
			{
				String str = request.getParameter(key);
				if (str.trim().equals(""))
					return defaultValue;
				return Long.parseLong(request.getParameter(key));
			}
		}
		catch (Exception ex)
		{
			return 0;
		}
	}

	/**
	 * 从Request中取得long值
	 * @param key
	 * @return
	 */
	public long getLong(String key)
	{
		return getLong(key, 0);
	}

	/**
	 * 返回数组取得多个同名参数值
	 * @param key
	 * @param defaultValue 用于转换失败时作为默认值
	 * @return float[]
	 */
	public float[] getFloatArray(String key, float defaultValue)
	{
		try
		{
			String _v[] = request.getParameterValues(key);
			if (_v != null && _v.length > 0)
			{
				float[] _numArr = new float[_v.length];
				for (int i = 0; i < _v.length; i++)
				{
					try
					{
						_numArr[i] = Float.parseFloat(_v[i]);
					}
					catch (NumberFormatException e)
					{
						_numArr[i] = defaultValue;
					}
				}
				return _numArr;
			}
		}
		catch (Exception e)
		{
		}
		return new float[0];
	}

	/**
	 * 从Request中取得float值,如无值则返回缺省值
	 * @param request
	 * @param key
	 * @return float
	 */
	public float getFloat(String key, float defaultValue)
	{
		try
		{
			if (request.getParameter(key) == null)
			{
				return defaultValue;
			}
			else
			{
				String str = request.getParameter(key);
				if (str.trim().equals(""))
					return defaultValue;
				return Float.parseFloat(request.getParameter(key));
			}
		}
		catch (Exception ex)
		{
			return 0;
		}
	}

	/**
	 * 从Request中取得float值
	 * @param request
	 * @param key
	 * @return float
	 */
	public float getFloat(String key)
	{
		return getFloat(key, 0);
	}
	
	public double getDouble(String key, double defaultValue)
	{
		try
		{
			if (request.getParameter(key) == null)
			{
				return defaultValue;
			}
			else
			{
				String str = request.getParameter(key);
				if (str.trim().equals(""))
					return defaultValue;
				return Double.parseDouble(request.getParameter(key));
			}
		}
		catch (Exception ex)
		{
			return 0;
		}
	}
	public double getDouble(String key){
		return getDouble(key, 0);
	}

	/**
	 * 取得当前页URL,如有参数则带参数
	 * @return String
	 */
	@SuppressWarnings("unchecked")
	public String getCurrentUrl()
	{
		StringBuffer urlThisPage = new StringBuffer();
		urlThisPage.append(request.getRequestURI());
		Enumeration e = request.getParameterNames();
		String para = "";
		String values = "";
		urlThisPage.append("?");
		if (e.hasMoreElements())
		{
			while (e.hasMoreElements())
			{
				para = String.valueOf(e.nextElement());
				values = request.getParameter(para);
				urlThisPage.append(para);
				urlThisPage.append("=");
				urlThisPage.append(values);
				urlThisPage.append("&");
			}
		}
		return urlThisPage.substring(0, urlThisPage.length() - 1);
	}

	/**
	 * 取得当前页URL,如有参数则带参数,但多个同名参数以separator合并为一个参数
	 * @param separator
	 * @return String
	 */
	@SuppressWarnings("unchecked")
	public String getCurrentUrlUniteParameter(String separator)
	{
		StringBuffer urlThisPage = new StringBuffer();
		urlThisPage.append(request.getRequestURI());
		Enumeration e = request.getParameterNames();
		String para = "";
		String values = "";
		urlThisPage.append("?");
		if (e.hasMoreElements())
		{
			while (e.hasMoreElements())
			{
				para = String.valueOf(e.nextElement());
				values = getStringValues(para, separator);
				urlThisPage.append(para);
				urlThisPage.append("=");
				urlThisPage.append(values);
				urlThisPage.append("&");
			}
		}
		return urlThisPage.substring(0, urlThisPage.length() - 1);
	}

	/**
	 * 取得当前页URL,如有参数则带参数,但多个同名参数以","合并为一个参数
	 * @param separator
	 * @return String
	 */
	public String getCurrentUrlUniteParameter()
	{
		return getCurrentUrlUniteParameter(",");
	}

	/**
	 * 取得申请的URL,不包含上下文路径
	 * @return String
	 */
	public String getRequestURI()
	{
		String url = this.request.getRequestURI();
		String ctxPath = this.request.getContextPath();
		int len = ctxPath.length();
		return url.substring(len);
	}

	/**
	 * 取的前面页面的地址
	 * @return String
	 */
	public String getRefererURL()
	{
		return this.request.getHeader("referer");
	}

	/**
	 * 取得请求中所有的参数集合形成一个map,根据remainArray参数决定返回字符串数组或字符串
	 * @param remainArray 是否保留为数组,否则以separator分隔成一个字符串
	 * @param separator 分隔符
	 * @param isSecure 是否过滤
	 * @return Map
	 */
	@SuppressWarnings("unchecked")
	public Map getParameterValueMap(boolean remainArray, String separator, boolean isSecure)
	{
		Map map = new HashMap();
		Enumeration params = request.getParameterNames();
		while (params.hasMoreElements())
		{
			String key = params.nextElement().toString();
			// 是否保留为数组
			if (remainArray)
			{
				map.put(key, getStringArray(key, false, isSecure));
			}
			else
			{
				//判断值是否为空，如果为空则不加入map中
				//zyg修改 2011-6-30
				String value= getStringValues(key, separator, isSecure).trim();
				if(value!=null && value.length()>0)
					map.put(key, getStringValues(key, separator, isSecure));
			}
		}
		return map;
	}

	/**
	 * 取得请求中所有的参数集合形成一个map,根据remainArray参数决定返回字符串数组或字符串
	 * @param remainArray 是否保留为数组,否则以","分隔成一个字符串
	 * @param isSecure 是否过滤
	 * @return Map
	 */
	@SuppressWarnings("unchecked")
	public Map getParameterValueMap(boolean remainArray, boolean isSecure)
	{
		return getParameterValueMap(remainArray, ",", isSecure);
	}
	
	public Date getDate(String key) {
		return getDate(key, "yyyy-MM-dd", null);
	}
	
	public Date getDate(String key, String format) {
		return getDate(key, format, null);
	}
	
	public Date getDate(String key, Date defValue) {
		return getDate(key, "yyyy-MM-dd", defValue);
	}
	
	public Date getDate(String key, String format, Date defValue) {
		String value = getString(key);
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		Date d = null;
		try {
			d = sdf.parse(value);
			return d;
		} catch (ParseException e) {
			e.printStackTrace();
			return defValue;
		}
	}
}
